package com.zhkc.wisdom.common.feign;

import com.zhkc.wisdom.common.configure.constant.ConfigureConstant;
import feign.Client;
import feign.Contract;
import feign.Feign;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;


@Slf4j
@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnProperty(prefix = ConfigureConstant.ZHKC_PROPERTIES_PREFIX
        + ".feign", name = "enabled", havingValue = "true", matchIfMissing = false)
public class FeignHttpClientAutoConfiguration {

    @PostConstruct
    public void init() {
        log.info("init FeignHttpClientAutoConfiguration...");
    }


    @Bean
    @ConditionalOnMissingBean({OkHttpClient.class})
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(Duration.ofSeconds(10))
                .readTimeout(Duration.ofSeconds(30))
                .addInterceptor(new LoggingInterceptor())
                .build();
    }

    static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long start = System.nanoTime();
            log.info(String.format("Feign发送请求 %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));
            Response response = chain.proceed(request);
            long end = System.nanoTime();
            log.info(String.format("Feign响应请求 for %s in %.1fms%n%s",
                    response.request().url(), (end - start) / 1e6d, response.headers()));
            return response;
        }
    }
}